<template>
  <div>
    <div id="mapContainer"></div>
    <div id="panel">
      <el-button type="primary" @click="initMap" size="small">加载地图与规划路线</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
// 声明全局变量类型
declare global {
  interface Window {
    map: any; // 或者具体的地图类型，如果可以确定的话
  }
}

const initMap = () => {
  if (!window.map) {
    // 初始化地图
    window.map = new (window as any).TMap.Map('mapContainer', {
      center: new (window as any).TMap.LatLng(39.980619, 116.321277),
      zoom: 14
    });

    // WebServiceAPI 请求 URL（驾车路线规划默认会参考实时路况进行计算）
    const url = "https://apis.map.qq.com/ws/direction/v1/driving/";
    url += "?from=39.984039,116.307630";
    url += "&to=39.977263,116.337063";
    url += "&output=jsonp&callback=cb";
    url += "&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77";

    // 发起 JSONP 请求，获取路线规划结果
    jsonp_request(url);
  }
};

// 浏览器调用 WebServiceAPI 需要通过 Jsonp 的方式，此处定义了发送 JOSNP 请求的函数
const jsonp_request = (url) => {
  const script = document.createElement('script');
  script.src = url;
  document.body.appendChild(script);
};

// 定义请求回调函数，在此拿到计算得到的路线，并进行绘制
window.cb = (ret) => {
  const coords = ret.result.routes[0].polyline,
      pl = [];
  // 坐标解压（返回的点串坐标，通过前向差分进行压缩）
  const kr = 1000000;
  for (let i = 2; i < coords.length; i++) {
    coords[i] = Number(coords[i - 2]) + Number(coords[i]) / kr;
  }
  // 将解压后的坐标放入点串数组 pl 中
  for (let i = 0; i < coords.length; i += 2) {
    pl.push(new (window as any).TMap.LatLng(coords[i], coords[i + 1]));
  }

  display_polyline(pl); // 显示路线

  // 标记起终点 marker
  const marker = new (window as any).TMap.MultiMarker({
    id: 'marker-layer',
    map: window.map,
    styles: {
      start: new (window as any).TMap.MarkerStyle({
        width: 25,
        height: 35,
        anchor: { x: 16, y: 32 },
        src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png'
      }),
      end: new (window as any).TMap.MarkerStyle({
        width: 25,
        height: 35,
        anchor: { x: 16, y: 32 },
        src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png'
      })
    },
    geometries: [
      {
        id: 'start',
        styleId: 'start',
        position: new (window as any).TMap.LatLng(39.984039, 116.307630307503)
      },
      {
        id: 'end',
        styleId: 'end',
        position: new (window as any).TMap.LatLng(39.977263, 116.337063)
      }
    ]
  });
};

const display_polyline = (pl) => {
  // 创建 MultiPolyline 显示折线
  const polylineLayer = new (window as any).TMap.MultiPolyline({
    id: 'polyline-layer', // 图层唯一标识
    map: window.map, // 绘制到目标地图
    // 折线样式定义
    styles: {
      style_blue: new (window as any).TMap.PolylineStyle({
        color: '#3777FF', // 线填充色
        width: 8, // 折线宽度
        borderWidth: 5, // 边线宽度
        borderColor: '#FFF', // 边线颜色
        lineCap: 'round' // 线端头方式
      })
    },
    // 折线数据定义
    geometries: [
      {
        id: 'pl_1', // 折线唯一标识，删除时使用
        styleId: 'style_blue', // 绑定样式名
        paths: pl
      }
    ]
  });
};
</script>

<style scoped>
html,
body {
  height: 100%;
  margin: 0px;
  padding: 0px;
  overflow: hidden;
}

#mapContainer {
  position: relative;
  width: 100%;
  height: 100%;
}

#panel {
  position: absolute;
  background: #fff;
  width: 200px;
  padding: 20px;
  z-index: 9999;
  top: 10px;
  left: 10px;
}
</style>